#include "storage/disk_scheduler.h"

namespace boltDB {
DiskScheduler::DiskScheduler(DiskManager *disk_manager)
    : disk_manager_(disk_manager) {
  // 开启后台工作线程
  background_thread_.emplace([&] { StartWorkerThread(); });
}

DiskScheduler::~DiskScheduler() {
  // 放入空元素去暂停
  request_queue_.Put(std::nullopt);
  if (background_thread_.has_value()) {
    background_thread_->join();
  }
}

void DiskScheduler::Schedule(DiskRequest r) {
  auto resquest = std::optional<DiskRequest>(std::move(r));
  request_queue_.Put(std::move(resquest));
}

void DiskScheduler::StartWorkerThread() {
  while (true) {
    auto request = request_queue_.Get();
    if (request == std::nullopt) {
      return;
    }
    if (request->is_write_) {
      disk_manager_->WritePage(request->page_id_, request->data_);
      request->is_ok_.set_value(true);
    } else {
      disk_manager_->ReadPage(request->page_id_, request->data_);
      request->is_ok_.set_value(true);
    }
  }
}
}  // namespace boltDB